package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.ConsoleDao;
import com.lei.springbootpractice.pojo.ConsolePojo;
import com.lei.springbootpractice.pojo.ConversationPojo;
import com.lei.springbootpractice.pojo.UserPojo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class ConsoleService {
    @Autowired
    ConsoleDao consoleDao;
    
    @Autowired
    UserService userService;
    
    @Autowired
    ConversationService conversationService;
    
    @Autowired
    NotificationService notificationService;
    
    /**
     * 顾客发送消息给客服
     * 如果没有活跃对话，会自动创建新对话
     */
    @Transactional
    public boolean sendMessageFromCustomer(String customerId, String message) {
        try {
            // 1. 获取或创建对话
            ConversationPojo conversation = conversationService.getActiveConversationByCustomer(customerId);
            if (conversation == null) {
                conversation = conversationService.startNewConversation(customerId);
            }
            
            // 2. 创建消息
            ConsolePojo console = new ConsolePojo();
            console.setConversationId(conversation.getConversationId());
            console.setSenderId(customerId);
            console.setContent(message);
            
            // 3. 保存消息
            boolean result = consoleDao.insert(console) > 0;
            
            // 4. 更新对话的最后消息时间和未读计数
            if (result) {
                conversationService.updateLastMessageTime(conversation.getConversationId());
                // 用户发送消息，增加客服未读计数
                conversationService.incrementUnreadCount(conversation.getConversationId(), true);
                
                // 5. 创建通知给客服
                UserPojo customer = userService.getUserByUserID(customerId);
                String customerName = customer != null ? customer.getUserName() : "用户";
                notificationService.createNotification(
                    conversation.getCustomerServiceId(),
                    "customer_service",
                    "new_message",
                    conversation.getConversationId(),
                    message.length() > 100 ? message.substring(0, 100) + "..." : message,
                    customerName
                );
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 客服回复消息给顾客
     */
    @Transactional
    public boolean sendMessageFromCustomerService(String customerServiceId, String conversationId, String message) {
        try {
            // 1. 验证对话是否存在且属于该客服
            ConversationPojo conversation = conversationService.getConversationById(conversationId);
            if (conversation == null) {
                throw new RuntimeException("对话不存在");
            }
            if (!conversation.getCustomerServiceId().equals(customerServiceId)) {
                throw new RuntimeException("无权限访问此对话");
            }
            
            // 2. 检查对话状态，如果已关闭则不能发送消息
            if ("closed".equals(conversation.getStatus())) {
                throw new RuntimeException("对话已结束，无法发送消息");
            }
            
            // 3. 创建消息
            ConsolePojo console = new ConsolePojo();
            console.setConversationId(conversationId);
            console.setSenderId(customerServiceId);
            console.setContent(message);
            
            // 4. 保存消息
            boolean result = consoleDao.insert(console) > 0;
            
            // 5. 更新对话的最后消息时间和未读计数
            if (result) {
                conversationService.updateLastMessageTime(conversationId);
                // 客服发送消息，增加用户未读计数
                conversationService.incrementUnreadCount(conversationId, false);
                
                // 6. 创建通知给用户
                UserPojo customerService = userService.getUserByUserID(customerServiceId);
                String serviceName = customerService != null ? customerService.getUserName() : "客服";
                notificationService.createNotification(
                    conversation.getCustomerId(),
                    "customer",
                    "new_message",
                    conversationId,
                    message.length() > 100 ? message.substring(0, 100) + "..." : message,
                    serviceName
                );
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("发送消息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取对话的所有消息
     */
    public List<ConsolePojo> getConversationMessages(String conversationId) {
        QueryWrapper<ConsolePojo> wrapper = new QueryWrapper<>();
        wrapper.eq("conversation_id", conversationId)
               .orderByAsc("create_time");
        
        List<ConsolePojo> messages = consoleDao.selectList(wrapper);
        
        // 填充显示信息
        for (ConsolePojo message : messages) {
            UserPojo sender = userService.getUserByUserID(message.getSenderId());
            if (sender != null) {
                message.setSenderName(sender.getUserName());
                message.setSenderRole(sender.getRole());
                message.setIsFromCustomer("customer".equals(sender.getRole()));
            }
            
            // 格式化时间显示
            if (message.getCreateTime() != null && !message.getCreateTime().isEmpty()) {
                try {
                    // 如果时间格式需要转换，在这里处理
                    // 目前假设数据库返回的时间格式已经是我们需要的
                } catch (Exception e) {
                    message.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
                }
            } else {
                message.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
            }
        }
        
        return messages;
    }
    
    /**
     * 获取顾客的对话记录（如果存在活跃对话）
     */
    public List<ConsolePojo> getCustomerConversation(String customerId) {
        ConversationPojo conversation = conversationService.getActiveConversationByCustomer(customerId);
        if (conversation == null) {
            return java.util.Collections.emptyList();
        }
        
        return getConversationMessages(conversation.getConversationId());
    }
    
    /**
     * 检查顾客是否有对话记录
     */
    public boolean hasConversation(String customerId) {
        return conversationService.hasActiveConversation(customerId);
    }
    
    /**
     * 获取客服的对话列表（使用ConversationService）
     */
    public List<ConversationPojo> getCustomerListForCustomerService(String customerServiceId) {
        return conversationService.getActiveConversationsByService(customerServiceId);
    }
}
